// app.js
const api = require('./config/api');
const request = require('./utils/request');
const { removeStorage } = require('./utils/util');
let isLogining = false;
App({
  data: {},
  isIPhoneX: false, // 当前设备是否为 iPhone X
  kBottomSafeHeight: 0, // X 34 ，其余 0

  onLaunch(options) {
    console.log('options-------', options);
    // 展示本地存储能力
    const that = this;
    const token = wx.getStorageSync('token');
    if (token) {
      that.globalData.logining = true;
    } else {
      if (options?.path === 'pages/sceneTrainDetail/index') {
        wx.redirectTo({
          url:
            '/pages/sceneTrainDetail/index?trainingId=' +
            options.query?.trainingId,
        });
      }
    }
    this.checkIsIPhoneX();
  },
  /**
   * 获取openId, sessionKey, unionId
   */
  async getSwapData() {
    return new Promise((resolve) => {
      wx.login({
        success: async (response) => {
          if (response?.code) {
            const res = await request.get(api.authSwap, {
              code: response.code,
            });
            if (res?.httpStatus == 200) {
              const swapData = res?.data || {};
              this.globalData.swapData = swapData;
              wx.setStorageSync('swapData', swapData);
              resolve(swapData);
            } else {
              this.message(res?.msg);
              resolve(null);
            }
          } else {
            this.message();
            resolve(null);
          }
        },
        error: () => {
          this.message();
          resolve(null);
        },
      });
    });
  },
  async navTo(url) {
    if (this.isLogin()) {
      if (url === '/pages/index/index') {
        wx.switchTab({
          url: url,
        });
      } else {
        wx.navigateTo({
          url: url,
        });
      }
    } else {
      await this.login(url);
    }
  },

  /**
   * 返回本页面
   * @param {string} path 退出登录信息
   */
  backToPath(path) {
    const pages = getCurrentPages();
    pages.forEach((item, index) => {
      if (item.route.indexOf(path) !== -1) {
        wx.navigateBack({
          delta: pages.length - 1 - index,
        });
        return;
      }
    });
  },
  /**
   * 登录绑定用户信息
   */
  async login(url) {
    if (isLogining) return;
    isLogining = true;
    // 用户信息
    this.clearLogin();
    const profile = await new Promise((resolve) => {
      wx.getUserProfile({
        desc: '用于用户登录',
        success: (res) => {
          resolve(res);
          isLogining = false;
        },
        error: () => {
          this.message('授权失败');
          resolve(null);
        },
        complete: () => {
          isLogining = false;
        },
      });
    });
    this.globalData.userInfo = profile?.userInfo;
    wx.setStorageSync('userInfo', profile?.userInfo);
    // 获取openId, sessionKey, unionId
    await this.getSwapData();

    wx.navigateTo({
      url: '/pages/login/index?url=' + url,
    });
    return profile?.userInfo;
  },
  /**
   * 微信登录
   */
  async wxLogin(profile) {
    const userInfo = this.globalData.userInfo;
    const swapData = this.globalData.swapData;
    const { encryptedData, iv } = profile;
    if (!swapData) {
      await this.getSwapData();
      this.message('登录失败！');
      return false;
    }
    let params = {
      encryptedData,
      ivStr: iv,
      headUrl: userInfo?.avatarUrl,
      gender: userInfo?.gender,
      nickname: userInfo?.nickName,
      sessionKey: swapData?.sessionKey,
      wxUnionid: swapData?.unionId,
      wxOpenid: swapData?.openid,
    };

    // 有邀请人信息
    if (wx.getStorageSync('invite_user_id')) {
      params['sourceId'] = wx.getStorageSync('invite_user_id');
      params['registerType'] = 2;
    } else if (wx.getStorageSync('invite_channel')) {
      params['sourceId'] = wx.getStorageSync('invite_channel');
      params['registerType'] = 3;
    } else {
      params['registerType'] = 1;
    }
    const res = await request.post(api.authBind, params);
    if (res?.httpStatus === 200) {
      wx.setStorageSync('phone', res.data.phone);
      wx.setStorageSync('token', res.data.token);
      wx.setStorageSync('userId', res.data.userId);

      return true;
    } else {
      this.message(res?.msg || '登录失败！');
    }
    return false;
  },
  // 获取患者列表
  getPatientList: async function () {
    const userId = wx.getStorageSync('userId');
    const res = await request.get(
      api.getPatientList + '/' + userId,
      {},
      { loading: false }
    );
    if (res.httpStatus === 200) {
      if (res.data.length > 0) {
        const index = res.data.findIndex((value) => value.isDefault === 1);
        res.data[index].age = res.data[index].monthAgeStr;
        wx.setStorageSync('patientInfo', res.data[index]);
      } else {
        wx.removeStorageSync('patientInfo');
      }
    }
  },
  /**
   * 是否已经登录
   */
  isLogin() {
    const token = wx.getStorageSync('token');
    return !!token;
  },

  /**
   * 清除登录状态
   */
  clearLogin() {
    wx.removeStorageSync('token');
    wx.removeStorageSync('phone');
    wx.removeStorageSync('swapData');
    wx.removeStorageSync('userInfo');
    wx.removeStorageSync('patientInfo');
    wx.removeStorageSync('userId');
    this.globalData.logining = false;
    this.globalData.swapData = null;
    this.globalData.userInfo = null;
    this.removeQuestionStorage();
  },

  //绑定档案后直接加入活动场景
  joinActivityScene: async function () {
    let userId = wx.getStorageSync('userId');
    let activityTrainingId = wx.getStorageSync('activityId');
    const res = await request.post(api.joinTrain, {
      activityTrainingId,
      userId,
    });
    console.log('加入活动场景', res);
    if (res) {
      wx.showToast({
        title: res.msg,
        icon: 'none',
      });
      setTimeout(() => {
        // 返回活动页面
        this.backToPath('activity/practiceAward/index');
      }, 1000);
    }
  },

  /**
   * 新建/绑定患者时根据入口跳转不同页面
   */
  async handleGoPage() {
    // 1-预约就诊
    // 2-自我评估（AI视频评估）
    // 3-自我评估（问卷评估）
    // 4-首页弹窗-绑定新档案
    // 5-加入训练
    // 6-我的孩子-绑定新孩子
    // 7-首页治疗日记
    // 9-加入活动场景跳转拿好礼活动页
    // 10-"3-14岁评估"说明页
    const that = this;
    let entrance = that.globalData.createPatientEntrance;
    const pages = getCurrentPages();
    if (entrance === 1) {
      wx.redirectTo({
        url: '/pages/appointment/index',
      });
    } else if (entrance === 2) {
      pages.forEach((item, index) => {
        if (item.route.indexOf('videoAssessment/video') !== -1) {
          wx.navigateBack({
            delta: pages.length - 1 - index,
          });
          return;
        }
      });
      wx.redirectTo({
        url: '/pages/selfAssessment/videoAssessment/video',
      });
    } else if (entrance === 3) {
      wx.redirectTo({
        url: '/pages/selfAssessment/questionIndex',
      });
    } else if (entrance === 4) {
      wx.switchTab({
        url: '/pages/index/index',
      });
    } else if (entrance === 5) {
      this.handleJoinTraining();
    } else if (entrance === 6) {
      wx.redirectTo({
        url: '/pages/patientList/index',
      });
    } else if (entrance === 7) {
      wx.redirectTo({
        url: '/pages/diary/index',
      });
    } else if (entrance === 8) {
      pages.forEach((item, index) => {
        if (item.route.indexOf('evaluatedRecords/index') !== -1) {
          wx.navigateBack({
            delta: pages.length - 1 - index,
          });
          return;
        }
      });
      wx.redirectTo({
        url: '/pages/evaluatedRecords/index',
      });
    } else if (entrance === 9) {
      this.joinActivityScene();
    } else if (entrance === 10) {
      // 判断是否有评估结果
      let res = await request.get(
        api.getEvaluationResult,
        {},
        { loading: false }
      );
      if (res.data?.patientRecord) {
        wx.redirectTo({
          url: '/pages/activity/evaluationResult/index',
        });
      } else {
        wx.redirectTo({
          url: '/pages/activity/evaluationAnswer/index?isChild=1',
        });
      }
    } else {
      wx.switchTab({
        url: '/pages/index/index',
      });
    }
  },
  async handleJoinTraining() {
    let trainingId = wx.getStorageSync('trainingId');
    let patientInfo = wx.getStorageSync('patientInfo');
    if (!patientInfo?.id) {
      return;
    }
    // 新建孩子档案后直接加入训练
    const res = await request.post(
      api.joinTraining,
      {
        bindBeforeId: trainingId,
        patientId: patientInfo.id,
      },
      { loading: false }
    );

    if (res.httpStatus === 200) {
      let { startDate, trainingName } = res.data.trainingTemplateInfo;
      let { detailId, trainingType, questionnaireId } =
        res.data.trainingDetailInfo;
      let trainingId1 = res.data.trainingDetailInfo.trainingId;
      let { isNeedEject } = res.data;
      wx.redirectTo({
        url: `/pages/practiceJoin/index?startDate=${startDate}&trainingId=${trainingId1}&trainingName=${trainingName}&detailId=${detailId}&trainingType=${trainingType}&questionnaireId=${questionnaireId}&isNeedEject=${isNeedEject}`,
      });
    } else {
      let pages = getCurrentPages();
      let key = this.globalData.createPatientType === 2 ? 3 : 2;
      let delta = this.globalData.isJoinedLogin ? key : key + 1;
      pages.forEach((item, index) => {
        if (item.route.indexOf('sceneTrainDetail/index') !== -1) {
          wx.navigateBack({
            delta: delta,
          });
        }
      });
      let info = wx.getSystemInfoSync().system;
      let isios = info.indexOf('ios') !== -1;

      if (isios) {
        wx.navigateTo({
          url: '/pages/sceneTrainDetail/index?trainingId=' + trainingId,
        });
      }
      setTimeout(() => {
        wx.showToast({
          title: res.msg ? res.msg : '加入失败',
          icon: 'none',
        });
      }, 600);
    }
  },
  /**
   * 完成训练任务后返回指定页面
   */
  handleFinishTaskBack() {
    // 1.首页任务进来
    // 2.空缺任务列表进来
    // 3.开始第一次任务进来
    // 4.训练任务详情进来
    // 5.从“参加训练拿实物好礼”页面进来
    const that = this;
    let finishTask = that.globalData.finishTaskEntrance;
    let isVacancyIndex = that.globalData.isVacancyIndex;

    console.log('finishTask--', finishTask);
    console.log('isVacancyIndex--', isVacancyIndex);
    const pages = getCurrentPages();
    if (finishTask === 1) {
      wx.switchTab({
        url: '/pages/index/index',
      });
    } else if (finishTask === 2) {
      if (isVacancyIndex === 1) {
        wx.switchTab({
          url: '/pages/index/index',
        });
      } else {
        pages.forEach((item, index) => {
          if (item.route.indexOf('practiceVacancy/index') !== -1) {
            wx.navigateBack({
              delta: 1,
            });
          }
        });

        wx.redirectTo({
          url: '/pages/practiceVacancy/index',
        });
      }
    } else if (finishTask === 3) {
      wx.switchTab({
        url: '/pages/index/index',
      });
    } else if (finishTask === 4) {
      let trainingId = wx.getStorageSync('trainingId');
      pages.forEach((item, index) => {
        if (item.route.indexOf('sceneDetail/index') !== -1) {
          wx.navigateBack({
            delta: 1,
          });
          return;
        }
      });
    } else if (finishTask === 5) {
      // 返回活动页面
      this.backToPath('activity/practiceAward/index');
    } else {
      wx.switchTab({
        url: '/pages/index/index',
      });
    }
  },

  // 判断设备是否为 iPhone X
  checkIsIPhoneX: function () {
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        var safeBottom = res.screenHeight - res.safeArea.bottom;
        that.kBottomSafeHeight = safeBottom;
        //根据安全高度判断
        if (safeBottom === 34) {
          that.isIPhoneX = true;
        }
      },
    });
  },
  /**
   * 清空 3-14岁问卷 答题缓存
   */
  removeQuestionStorage() {
    removeStorage('evaluationUserId');
    removeStorage('evaluationPatientId');
    removeStorage('evaluationAnswerList');
    removeStorage('evaluationIsChild');
  },

  globalData: {
    // openId, sessionKey, unionId
    swapData: null,
    // 用户信息
    userInfo: null,
    // 登录状态
    logining: false,
    //是否点击预约
    appointmentUrl: '',
    // indexUrl:false,
    // 创建绑定患者入口
    createPatientEntrance: '',
    // 绑定孩子档案是扫码还是搜索档案号 1--扫码 2-搜索档案号
    createPatientType: 1,
    resultBack: false,
    // 去做任务入口
    finishTaskEntrance: 0,
    // 从首页空缺列表进入
    isVacancyIndex: 0,
    // 是否点击了下一项任务
    isHandleNext: 0,
    // 是否是第一个任务
    isFirstTask: false,
    // 记录加入训练时是否登录
    isJoinedLogin: false,
  },
});
